package logic

import (
	"context"
	"fmt"
	"my-zero-tiktok/apps/user/models"
	"my-zero-tiktok/common/constant"
	"my-zero-tiktok/common/xerr"
	"strconv"
	"time"

	"my-zero-tiktok/apps/user/pb/pb"
	"my-zero-tiktok/apps/user/rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type FollowUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFollowUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FollowUserLogic {
	return &FollowUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// FollowUser 关注
func (l *FollowUserLogic) FollowUser(in *pb.RelationRequest) (*pb.Empty, error) {
	// 建立关注数据
	nowTime := time.Now()
	_, err := l.svcCtx.RelationModel.Insert(l.ctx, &models.Relation{
		UserId:     in.FromId,
		ToUserId:   in.ToId,
		CreateTime: nowTime.Unix(),
		UpdateTime: nowTime.Unix(),
	})

	if err != nil {
		return nil, xerr.New(xerr.UserFollowError)
	}

	// 我关注的人
	followKey := fmt.Sprintf("%s:%d", constant.FollowKey, in.FromId)
	_, _ = l.svcCtx.Redis.ZaddCtx(l.ctx, followKey, nowTime.Unix(), strconv.FormatInt(in.ToId, 10))
	// 关注人的粉丝
	fanKey := fmt.Sprintf("%s:%d", constant.FanKey, in.ToId)
	_, _ = l.svcCtx.Redis.ZaddCtx(l.ctx, fanKey, nowTime.Unix(), strconv.FormatInt(in.FromId, 10))
	return &pb.Empty{}, nil
}
